import { interpreter } from "@/api/request";
import { getHotQuestionList } from "@/api/zixun";
import debounce from "@/utils/debounce";
import { computed, ref } from "vue";

export interface Hot {
  id: number;
  content: string;
  robot_id: number;
  hot_index: number;
  created_at: string;
  updated_at: string;
}
export default function useHot() {
  const pagination = ref<{
    size: number;
    page: number;
    currentCase: number | null;
  }>({
    size: 3,
    page: 0,
    currentCase: null
  });
  const hot = ref<Array<Hot>>([]);

  const getHotList = async (id?: number) => {
    const [err, res] = await interpreter(getHotQuestionList(id));
    if (!err) {
      hot.value = res;
    }
  };

  const getThree = computed(() => {
    if (hot.value.length < 3) {
      return hot.value;
    }
    const { size, page } = pagination.value;
    const list = hot.value.slice(page, size + page);
    if (list.length === 3) {
      return list;
    }
    const diff = hot.value.slice(0, 3 - list.length);
    return [...list, ...diff];
  });

  const changeHot = debounce(
    () => {
      const { page, size } = pagination.value;
      const currentLen = hot.value.length;
      if (currentLen <= 3) {
        uni.showToast({
          title: "没有更多了",
          icon: "none"
        });
        return;
      }
      if (currentLen) {
        pagination.value.page = (page + size) % currentLen;
      }
    },
    500,
    true
  );

  return {
    hot,
    getThree,
    getHotList,
    changeHot
  };
}
